package com.gw.vip.center.sign;

import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author GW
 * @Version 1.0
 * @Description
 * @since 2020/12/12 15:05
 */
@Service
public class Sha256SignCreator implements SignCreator {
    @Override
    public String createSign(String message, String signKey) {
        try {
            // 创建加密对象
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256".intern());
            // 传入要加密的字符串,按指定的字符集将字符串转换为字节流
            messageDigest.update((message + "&key=" + signKey).getBytes("UTF-8".intern()));
            byte byteBuffer[] = messageDigest.digest();
            // 將 byte转换为16进制string
            StringBuffer strHexString = new StringBuffer();
            for (int i = 0; i < byteBuffer.length; i++) {
                String hex = Integer.toHexString(0xff & byteBuffer[i]);
                if (hex.length() == 1) {
                    strHexString.append('0');
                }
                strHexString.append(hex);
            }
            return strHexString.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
